<template>
  <div class="chat-container">
    <ul class="title">
      <li style="--i:1;">讯</li>
      <li style="--i:2;">飞</li>
      <li style="--i:3;">智</li>
      <li style="--i:4;">能</li>
      <li style="--i:5;">助</li>
      <li style="--i:6;">手</li>
    </ul>
    <div class="chat-messages" ref="chatWindow">
      <div v-for="(item, index) in messages" :key="index" class="chat-history">
        <div class="user-msg" v-if="item.role === 'user'">
          <div class="msg-right">{{ item.content }}</div>
          <img src="@/assets/userImage.jpg" class="avatar">
        </div>
        <div class="chat-msg" v-if="item.role === 'system' || item.role === 'assistant'">
          <img src="../assets/image2.png" class="avatar">
          <div class="msg-left-container">
            <MdPreview :model-value="item.content" class="msg-left" v-if="item.content"></MdPreview>
            <img src="@/assets/loading.gif" alt="加载中..." class="loading-gif" v-else>
          </div>
        </div>
      </div>
    </div>

    <div class="input-area">
      <button @click="deepThinking = !deepThinking" :class="['toggle-button', { active: deepThinking }]">
        深度思考
      </button>
      <button @click="networkSearch = !networkSearch" :class="['toggle-button', { active: networkSearch }]">
        网络搜索
      </button>
      <button @click="clearMessages" class="toggle-button">清除历史</button>
      <send_input :isSend="loading" @send_message="sendMessage" ref="sendInput"></send_input>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue'
import Send_input from "./SendInput.vue"
import { MdPreview } from 'md-editor-v3'
import { useMessagesStore } from '@/stores/canMessages'; // 引入 store
import { useCanSendStore } from '@/stores/canSend';
import { useChatWithAIStore } from '@/stores/canChatWithAI';
import { useDisplayMessage } from '@/stores/canDisplayMessage';
import { onMounted } from 'vue'

onMounted(() => {
  canMessagesStore.addMessage({
    role: 'system',
    content: '您好！我是讯飞星火AI助手，有什么可以帮您的？'
  })
})

const canMessagesStore = useMessagesStore(); // 初始化 store
const canSendStore = useCanSendStore();
const canChatWithAIStore = useChatWithAIStore();
const canDisplayMessage = useDisplayMessage();

const messages = canMessagesStore.messages; 
// 响应式数据 -> 现在直接从 store 获取
const loading = ref(false)
const chatWindow = ref<HTMLDivElement | null>(null)
const sendInput = ref<InstanceType<typeof Send_input> | null>(null)

// 新增的状态
const deepThinking = ref(false)
const networkSearch = ref(false)

// 当前打字机打印的字符位置
const charIndex = ref(0)
// 当前接收到的数据
const currentAns = ref('')
// 判断是否在打印
const isTyping = ref(false)
// 新增：消息队列
const messageQueue = ref<string[]>([])
const typingId = ref<ReturnType<typeof setTimeout> | null>(null)
// 数据是否接收完
const isEnd = ref(false)
// 头像的 URL
const imgUrl = ref('../static/Rob-img.png')

// 防抖滚动到底部
let scrollTimeout: ReturnType<typeof setTimeout> | null = null

const scrollToBottom = () => {
  if (scrollTimeout) clearTimeout(scrollTimeout)

  scrollTimeout = setTimeout(() => {
    if (chatWindow.value) {
      chatWindow.value.scrollTop = chatWindow.value.scrollHeight
    }
  }, 50)
}

// 清除历史消息
const clearMessages = () => {
  canMessagesStore.clearMessages(); // 调用 store 方法
}

// 打字效果
const typeWriterEffect = () => {
  if (isTyping.value || !currentAns.value) {
    return; // 如果已经在打字或没有内容，则不执行
  }

  isTyping.value = true;

  const animate = () => {
    if (charIndex.value < currentAns.value.length) {
      // 更新最后一条消息的内容，确保在最后添加新字符
      const lastMessage = canMessagesStore.getLastMessage();
      if (lastMessage && lastMessage.role === 'assistant') {
        // 在现有内容基础上追加新字符
        canMessagesStore.updateLastMessageContent(lastMessage.content + currentAns.value[charIndex.value])
      } else {
        // 如果最后一条不是 assistant 消息，则添加新的 assistant 消息
        canMessagesStore.addMessage({ role: 'assistant', content: currentAns.value.slice(0, charIndex.value + 1) });
      }
      charIndex.value++
      scrollToBottom()
      typingId.value = setTimeout(animate, 20)
    } else {
      if (typingId.value !== null) {
        clearTimeout(typingId.value)
        typingId.value = null
      }
      isTyping.value = false;
      currentAns.value = ''; // 清空当前答案

      // 更换头像
      if (isEnd.value) {
        const avatars = document.getElementsByClassName("avatar")
        if (avatars.length > 0) {
          // 断言为 HTMLImageElement 类型
          (avatars[avatars.length - 1] as HTMLImageElement).src = imgUrl.value
        }
        isEnd.value = false
      }

      processNextMessage(); // 继续处理下一条消息
    }
  };

  animate();
};

// 新增：处理队列中的下一条消息
const processNextMessage = () => {
  if (messageQueue.value.length > 0 && !isTyping.value) {
    const nextMessage = messageQueue.value.shift();
    if (nextMessage) {
      currentAns.value = nextMessage;
      charIndex.value = 0;
      scrollToBottom();
      typeWriterEffect();
    }
  }
};

// 监听store的变化
watch(
  () => canChatWithAIStore.chatWithAI, // 监听 getChatWithAI 返回的具体值
  (newVal) => {
    if (newVal) {
      sendMessage(canChatWithAIStore.getDisplayChatWithAI()); // 调用函数 sendMessage 并传递新的值
    }
  }
);

// 发送消息处理
const sendMessage = async (userMessage?: string) => {
  let actualPrompt = '';
  if (userMessage && !sendInput.value){
    networkSearch.value = true
    actualPrompt = canChatWithAIStore.getChatWithAI();
  }
  const message = userMessage || (sendInput.value ? sendInput.value.message : '')
  charIndex.value = 0

  if (!message.trim() || loading.value) {
    return
  }

  // 清除之前的定时器
  if (typingId.value !== null) {
    clearTimeout(typingId.value)
    typingId.value = null
  }

  // 添加用户消息
  canMessagesStore.addMessage({ role: 'user', content: message }) // 使用 store 添加消息
  if (sendInput.value) {
    sendInput.value.message = ''
  }
  loading.value = true
  scrollToBottom()


  try {
    await fetchStreamResponse(actualPrompt, (partialContent) => {
      currentAns.value = partialContent
      typeWriterEffect()
    }, deepThinking.value, networkSearch.value)
  } catch (error) {
    canMessagesStore.updateLastMessageContent('抱歉，请求处理时出现错误。请稍后再试。')
  } finally {
    loading.value = false
    isEnd.value = true
    canSendStore.setCanSend(true)
    scrollToBottom()
  }
}

// 讯飞星火大模型API请求（支持流式响应）
const fetchStreamResponse = async (
  prompt: string, 
  callback: (content: string) => void,
  deepThinking: boolean,
  networkSearch: boolean
): Promise<string> => {
  const data = {
    question: prompt,
    userId: 123,
    deepThinking: deepThinking,
    networkSearch: networkSearch,
    messages: canMessagesStore.messages.filter(msg => !(msg.content === '')) // 使用 store 中的消息
  }

  const response = await fetch('http://localhost:8080/chat', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify(data)
  })

  if (!response.ok) {
    throw new Error('网络响应异常')
  }

  if (!response.body) {
    throw new Error('响应体为空，无法读取流式数据')
  }

  const reader = response.body.getReader()
  const decoder = new TextDecoder()
  let aiContent = ''

  while (true) {
    const { done, value } = await reader.read()
    if (done) break

    const chunk = decoder.decode(value, { stream: true })
    aiContent += chunk
    currentAns.value = aiContent

    if (!isTyping.value) {
      typeWriterEffect()
    }
  }

  isEnd.value = true
  return aiContent
}

// 监听 canDisplayMessage.getDisplayMessage() 的变化
watch(
  () => canDisplayMessage.getDisplayMessage(), // 监听 A Store 中 B 变量的变化
  (newVal) => {
    if (newVal) {
      // 如果当前正在打字，则将新消息加入队列
      if (isTyping.value || currentAns.value) {
        messageQueue.value.push(newVal);
      } else {
        addBToMessagesAndType(newVal); // 否则直接处理
      }
    }
  }
);

// 新增函数：将 A Store 中的 B 变量添加到 messages 并触发打字效果
const addBToMessagesAndType = (displayMessage: string) => {
  if (!displayMessage) {
    console.warn('B variable is empty or not available in the A store')
    return
  }

  charIndex.value = 0
  currentAns.value = displayMessage // 设置当前答案为 displayMessage 的值

  // 如果已经有消息存在，则在最后一条消息后追加换行符
  if (canMessagesStore.messages.length > 0) {
    const lastMessage = canMessagesStore.getLastMessage();
    if (lastMessage.role === 'assistant') {
      canMessagesStore.updateLastMessageContent(lastMessage.content + '\n\n')
    } else {
      canMessagesStore.addMessage({ role: 'assistant', content: '\n\n' });
    }
  } else {
    // 否则添加新的 assistant 消息
    canMessagesStore.addMessage({ role: 'assistant', content: '' });
  }

  scrollToBottom()

  // 开始打字效果
  typeWriterEffect()
}
</script>

<style scoped>
.chat-container {
  width: 100%;
  max-width: 100%;
  margin: 0;
  padding: 0;
  border: none;
  background-color: #f5f7fa;
  height: 90vh;
  display: flex;
  flex-direction: column;
}

.input-area {
  display: flex;
  gap: 12px;
  padding: 10px 0;
  background: white;
  border-top: 1px solid #ebeef5;
  flex-shrink: 0;
}

.title {
  display: flex;
  justify-content: center;
  padding: 0;
  margin: 0;
  font-family: 'PingFang SC', 'Microsoft YaHei', sans-serif;
}

.title li {
  display: inline-block;
  list-style: none;
  font-size: 2rem;
  font-weight: 500;
  color: #333;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  animation: shine 2s linear infinite;
  animation-delay: calc(0.2s * var(--i));
  transition: all 0.3s ease;
  margin: 0 2px;
}

.title {
  background: linear-gradient(90deg, #f8f9fa, #e9ecef);
  padding: 10px 20px;
  border-radius: 8px;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.05);
}

.title li {
  font-size: 1.8rem;
  font-weight: 500;
  color: #2c3e50;
  text-shadow: 0 0 8px rgba(64, 158, 255, 0.2);
  animation: techGlow 2.5s ease-in-out infinite;
}

@keyframes techGlow {
  0%, 100% {
    text-shadow: 0 0 8px rgba(64, 158, 255, 0.2);
  }
  50% {
    text-shadow: 0 0 12px rgba(64, 158, 255, 0.4);
  }
}

.chat-messages {
  flex: 1;
  overflow-y: auto;
  padding: 10px 0;
  display: flex;
  flex-direction: column;
}

@keyframes shine {
  0% {
    color: white;
    text-shadow: 0 0 10px #00b3ff, 0 0 20px #00b3ff, 0 0 40px #00b3ff;
  }

  30%,
  70% {
    color: white;
    filter: hue-rotate(360deg);
    text-shadow: 0 0 10px #00b3ff, 0 0 20px #00b3ff, 0 0 40px #00b3ff;
  }

  100% {
    color: transparent;
    box-shadow: none;
  }
}

.title {
  padding: 10px;
  font-weight: bolder;
  font-size: 22px;
  color: transparent;
}

.user-msg {
  display: flex;
  justify-content: flex-end;
  align-items: flex-start;
  background-color: #f5f7fa;
  margin-bottom: 8px;
  padding: 0 20px;
}

.chat-msg {
  display: flex;
  justify-content: flex-start;
  align-items: flex-start;
  background-color: #f5f7fa;
  margin-bottom: 8px;
  padding: 0 20px;
}

.msg-right,
.msg-left {
  font-size: 16px;
  line-height: 28px;
  padding: 10px;
  max-width: 80%;
  border-radius: 10px;
}

.msg-right {
  background-color: aquamarine;
  margin-left: auto;
  text-align: left;
  font-size: 16px;
}

.msg-left {
  background-color: white;
  margin-right: auto;
  text-align: left;
  font-size: 16px;
}

.avatar {
  width: 40px;
  height: 40px;
  flex-shrink: 0;
  text-align: left;
}

.toggle-button {
  padding: 8px 16px;
  border: none;
  border-radius: 4px;
  background-color: #f0f0f0;
  color: #333;
  cursor: pointer;
  transition: all 0.3s ease;
}

.toggle-button.active {
  background-color: #4caf50;
  color: white;
}

.loading-gif {
  width: 40px;
  height: 40px;
  margin-top: 8px;
}
.msg-left-container {
  flex: 1;
  padding: 10px;
}
</style>



